import fs from 'fs-extra';
import path from "path";
import { CopyXsdkLibrary, GradleBuild, ModifyGradle, recordApk, UploadApk } from './AndroidBuildUtil.js';
import { CmdOption } from '../../CmdOption.js';
import { toolchain } from '../../toolchain.js';
import { TaskResult } from '../../common/tasks/BastTask.js';
import { PrebuildAppData, PreBuildAppTask } from '../../common/tasks/PreBuildAppTask.js';
import { IBuildAppResult } from '../../typings.js';



/**
 * 导出laya的gradle工程
 */
class ExportLayaGradle {
    constructor(private cmdOption: CmdOption, private exportproj: string,
        private defines: string,
        private versionCode: string) { }
    async export() {
        if (!this.versionCode) {
            let s = fs.readFileSync(path.join(this.exportproj, 'app/build.gradle'), { 'encoding': 'utf-8' });
            this.versionCode = s.match(/versionCode\s+(\d+)/)![1] as string;
        } else {
            // await fs.remove(this.exportproj);
            // let cmd = new Cmd();
            // try {
            //     cmd.run("LayaAirIDE", ["--project=" + toolchain.params.workSpacePath, "--script=GameBuilder.build_android"]);
            // } catch (e) {
            //     toolchain.logParser.parseUnityBuildLog(cmd.output);
            //     if (toolchain.logParser.error) {
            //         await sendBuildFailureAlert(toolchain.logParser.error);
            //     }
            //     process.exit(1);
            // }
            
        }
    
        // 重写工程的targetversion,complieversion
        let appBuildPath = path.join(this.exportproj, 'app/build.gradle');
        let appBuild = fs.readFileSync(appBuildPath, { 'encoding': 'utf-8' });
        if (toolchain.params.channelCfg.targetSdkVersion) {
            appBuild = appBuild.replace(/targetSdkVersion\s+\d+/, 'targetSdkVersion ' + toolchain.params.channelCfg.targetSdkVersion);
        }
        appBuild = appBuild.replace(/compileSdkVersion\s+\d+/, 'compileSdkVersion ' + (toolchain.params.channelCfg.compileSdkVersion??"31"));
        if (toolchain.params.channelCfg.targetSdkVersion) {
            appBuild = appBuild.replace(/targetSdkVersion\s+\d+/, 'targetSdkVersion ' + toolchain.params.channelCfg.targetSdkVersion);
        }
        fs.writeFileSync(appBuildPath, appBuild, { 'encoding': 'utf-8' });        

        // 移除工程的 network_security_config
        let conchMainPath = path.join(this.exportproj, 'conch/src/main/AndroidManifest.xml');
        let conchMain = fs.readFileSync(conchMainPath, { 'encoding': 'utf-8' });
        fs.writeFileSync(conchMainPath, conchMain.replace('android:networkSecurityConfig="@xml/network_security_config"', ''), { 'encoding': 'utf-8' });        

        let bundleVersion = toolchain.params.channelCfg.bundleVersion! ?? toolchain.params.channelCfg.version!;
        return (bundleVersion ?? toolchain.params.version) + "." + this.versionCode;
    }
}

export class AndroidBuildLaya {
    static async run(cmdOption: CmdOption): Promise<TaskResult<IBuildAppResult>> {
        const prebuildResult = toolchain.taskHelper.getResult<PrebuildAppData>(PreBuildAppTask.name);

        const c = toolchain.params.channelCfg;
        let exportproj = path.join(toolchain.params.workSpacePath, '../export');
        const xsdkPath = path.join(cmdOption.oldToolsRoot, 'sdk/android/xsdk');

        // 导出laya的gradle工程
        let version = await new ExportLayaGradle(cmdOption, exportproj, prebuildResult?.data?.defines ?? "", prebuildResult?.data?.versionCode ?? "").export();

        // 将xsdkLibrary复制到laya的gradle工程中
        let changeXSdkPackage = await new CopyXsdkLibrary(xsdkPath, toolchain.params, exportproj, cmdOption).copy();

        // 将xsdkLibrary嵌入到laya的gradle工程中
        let gradleProperties = await new ModifyGradle('laya', exportproj, changeXSdkPackage, c.bundleId, "app").insert();

        // 构建gradle工程，生成apk/aab
        await new GradleBuild(exportproj, xsdkPath,gradleProperties, 'app').build(c.apk!.endsWith('.aab'));

        // 将构建好的apk/aab放到 hudson下 供内网下载
        let apkName = await new UploadApk(toolchain.params, exportproj, version, 'app').upload();

        // 记录该次构建信息到项目的build/apks.txt
        // await recordApk(apkName);
        return { success: true, errorCode: 0, data: { apkName, version } };
    }
}
